﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Alexinea.Autofac.Extensions.DependencyInjection;
using Autofac;
using AutoMapper;
using BestTrader.Cms.Core;
using BestTrader.Cms.Core.Options;
using BestTrader.Cms.Repository.SqlServer;
using BestTrader.Cms.RmmfSoftServices;
using BestTrader.Cms.Services;
using BestTrader.Cms.UserCenter.Filter;
using BestTrader.Cms.UserCenter.Validation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using BestTrader.Cms.IServices;

namespace BestTrader.Cms.UserCenter
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            #region Config

            services.Configure<DbOption>("BT.TEST", Configuration.GetSection("DbOption"));
            services.Configure<QiniuOption>("QINIU", Configuration.GetSection("QiniuOption"));
            services.Configure<SystemBankOption>("SYS.BANK", Configuration.GetSection("SystemBankOption"));
            services.Configure<YunpayOption>("YUNPAY", Configuration.GetSection("YunpayOption"));
            services.Configure<GomePayOption>("GOMEPAY", Configuration.GetSection("GomePayOption"));
            services.Configure<RmmsoftOption>("RMMSOFT", Configuration.GetSection("RmmsoftOption"));
            
            #endregion

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                    .AddCookie(options =>
                    {
                        options.LoginPath = "/Account/Index";
                        options.LogoutPath = "/Account/Logout";
                        options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
                    });
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            })
            .AddAntiforgery(options =>
            {
                // Set Cookie properties using CookieBuilder properties†.
                options.FormFieldName = "AntiforgeryKey_yilezhu";
                options.HeaderName = "X-CSRF-TOKEN-yilezhu";
                options.SuppressXFrameOptionsHeader = false;
            }).AddMvc(option =>
            {
                option.Filters.Add(new GlobalExceptionFilter());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddControllersAsServices()
            .AddFluentValidation(fv =>
            {
                fv.RegisterValidatorsFromAssemblyContaining<LoginModelValidation>();
                fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
            });

            #region HttpClient
            // [.NET Core 中正确使用 HttpClient 的姿势](https://www.cnblogs.com/willick/p/net-core-httpclient.html)
            services.AddHttpClient<YunPayClientService>();
            services.AddHttpClient<GomePayClientService>();
            #endregion

            #region AutoMapper

            services.AddAutoMapper();   // DI了AutoMapper中需要用到的服务，其中包括AutoMapper的配置类 Profile 

            #endregion

            #region AutoFac
            //[Autofac 使用经验](https://www.cnblogs.com/ideacore/p/7532041.html)
            var builder = new ContainerBuilder();
            builder.Populate(services);
            builder.RegisterAssemblyTypes(typeof(ManagerRoleRepository).Assembly)
                   .Where(t => t.Name.EndsWith("Repository"))
                   .InstancePerLifetimeScope()
                   .AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(typeof(ManagerRoleService).Assembly)
                 .Where(t => t.Name.EndsWith("Service"))
                 .InstancePerLifetimeScope()
                 .AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(typeof(RmmfSoftAccountService).Assembly)
                .InstancePerLifetimeScope()
                .Where(t => t.Name.EndsWith("Service"));

            return new AutofacServiceProvider(builder.Build());

            #endregion
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            //add NLog to ASP.NET Core
            loggerFactory.AddNLog();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
